﻿// <copyright file="UV4IncludeDirectoriesParser.cs" company="Horiba Medical">
//     Copyright (c) Horiba Medical. All rights reserved.
// </copyright>
// <summary>
//     Provides an include directories parser for UV4 project files.
// </summary>

namespace DoxyOutParser.CodeCheck
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Linq;
	using System.Text;
	using System.Xml;

	/// <summary>
	/// Parses include directories from a UV4 project file.
	/// </summary>
	public class UV4IncludeDirectoriesParser : IIncludeDirectoriesParser
	{
		/// <summary>
		/// The file which will be parsed.
		/// </summary>
		private string uv4ProjectFile;

		/// <summary>
		/// Initializes a new instance of the UV4IncludeDirectoriesParser class.
		/// </summary>
		/// <param name="projectFile">The file to parse.</param>
		public UV4IncludeDirectoriesParser(string projectFile)
		{
			// TODO Check the value of string and eventually check if exist or not.
			this.uv4ProjectFile = projectFile;
		}

		#region IIncludeDirsParser Members

		/// <summary>
		/// Returns a list of every include directories specified in a UV4 project file.
		/// </summary>
		/// <returns>The directory list.</returns>
		public string[] GetIncludeDirectoriesTable()
		{
			// Using XML document
			XmlDocument uv4Proj = new XmlDocument();
			uv4Proj.Load(this.uv4ProjectFile);

			XmlNodeList xmlIncludeElementNodeList = uv4Proj.GetElementsByTagName("IncludePath");
			foreach (XmlNode xmlNode in xmlIncludeElementNodeList)
			{
				if (this.GetFullXPath(xmlNode).Contains("Cads"))
				{
					string includeDirsData = xmlNode.InnerText;
					string[] dirsSeparators = { ";" };
					return includeDirsData.Split(dirsSeparators, StringSplitOptions.RemoveEmptyEntries);
				}
			}

			return null;
		}

		#endregion

		/// <summary>
		/// Gets the full path to an XML node.
		/// </summary>
		/// <param name="xmlNode">The XML node to parse.</param>
		/// <returns>The full path.</returns>
		private string GetFullXPath(XmlNode xmlNode)
		{
			string newFullPath = this.GetParentBrowsePath(xmlNode, xmlNode.Name);

			return newFullPath;
		}

		/// <summary>
		/// Gets the path to an XML node's parent.
		/// </summary>
		/// <param name="xmlNode">The XML node to parse.</param>
		/// <param name="xmlNodePath">The path to this node.</param>
		/// <returns>The path to the parent node.</returns>
		private string GetParentBrowsePath(XmlNode xmlNode, string xmlNodePath)
		{
			string xmlNewNodePath;
			if (xmlNode.ParentNode != null)
			{
				xmlNewNodePath = this.GetParentBrowsePath(xmlNode.ParentNode, xmlNode.ParentNode.Name + "/" + xmlNodePath);
			}
			else
			{
				xmlNewNodePath = xmlNodePath;
			}

			return xmlNewNodePath;
		}
	}
}
